<?php

    global $mikron;

    /*mysql_query('UPDATE T_USER SET `refamount` = 0');
    $logs = $mikron->Queries->Query('T_OPERATIONS_LOG');
    while($log = $logs->fetch())
    {
        if($log->source->value == 9)
        {
            //$c = $log->cabinet->value;
            //$c->winamount->value += $log->amount->value;
            //$c->Save();           
        }
        elseif($log->source->value == 7)
        {
            $c = $log->cabinet->value;
            $c->refamount->value += $log->amount->value;
            $c->Save();           
        }
    }
    return;
    */

    function InterestingStatistics()
    {
        $r = mysql_query('SELECT count(*) `cnt`, `user` FROM PLAYLOG GROUP by `user`;');
        $stat = Array();
        $count = mysql_num_rows($r);
        $more1 = 0;
        $more3 = 0;
        $more5 = 0;
        $all = 0;
        $max = 0;
        $max_user = 0;
        while($row = mysql_fetch_object($r))
        {
            $all += $row->cnt;
            if($row->cnt > $max)
            {
                $max = $row->cnt;
                $max_user = $row->user;
            }
            if($row->cnt > 7)
            {
                $stat[$row->user] = $row->cnt;
                $more1++;
                if($row->cnt > 21)
                {
                    $more3++;
                }
                if($row->cnt > 35)
                {
                    $more5++;
                }
            }
        }
        $max = round($max / 7, 2);
        $u = new T_USER($max_user);
        $maxusername = $u->login->value;
        $medium = round($all / 7 / $count, 2);
        echo "{{nicewindow style=silver caption=\"Это интересно...\"}}Всего $count игравших,
        из них $more1 играли более 1-го раза, $more3 играли более 3-х раз.
        <br />$more5 чел. это монстры, которые играли более 5 раз.
        <br />Среднее кол-во игр равно $medium.
        <br />Максимальное кол-во раз сыграл $maxusername — $max раз(а)!
        {{/nicewindow}}";
    }

    // echo $mikron->Cache->TimedFunctionContent('gamestats', 'getStat', 5);
    getStat();

    function getStat()
    {

        global $mikron;
        
        /**
        * подсчет суммы в проекте
        */
        $sum_in_project = 0;
        $r = $mikron->Queries->Query('GAME', null, null, null, null, null, null, Array('bank'));
        while($e = $r->fetch())
        {
            $s = $e->bank->value;
            $sum_in_project += is_null($s)?0:$s;
        }
        $r = $mikron->Queries->Query('T_USER', null, new Criterion('amount', 0, CR_MORE), null, null, null, null, Array('amount'));
        while($e = $r->fetch())
        {
            $s = $e->amount->value;
            $sum_in_project += is_null($s)?0:$s;
        }
        $r = $mikron->Queries->Query('T_EX_RECORD', null, new Criterion('status', 1), null, null, null, null, Array('amount'));
        while($e = $r->fetch())
        {
            $s = $e->amount->value;
            $sum_in_project += is_null($s)?0:$s;
        }

        $stat = Array();
        $stat_count = Array();
        $stat_zero_count = Array();

        $dt = time();
        $dt = date($mikron->Constants->DateTimeFormatMySQL, strtotime(date('Y-m-d', $dt)));
        $dt2 = MikronDateTime::BeautifulDate(strtotime($dt));

        $tbl_main = new html_table(null, null, '100%', 4, 0);
        $tbl_main->newcol(null, false, false, null, null, null, 'top');

        $summa = 0;
        $games_count = 0;
        $games_count_sum = 0;
        
        $result = mysql_query("SELECT sum(amount) summa, count(*) cnt, `game`
            FROM PLAYLOG
            WHERE `dt` > '$dt'
            GROUP by `game`
            ORDER by `game` ASC");
        while($row = mysql_fetch_object($result))
        {
            $game_id = $row->game;
            $gamename = $mikron->Queries->Query('GAME', null, new Criterion('id', $game_id))->fetch()->name->value;
            $sum = $row->summa;
            if(!array_key_exists($gamename, $stat))
            {
                $stat[$gamename] = 0;
                $stat_count[$gamename] = 0;
                $result2 = mysql_query("SELECT COUNT(*) zerocount FROM PLAYLOG WHERE `dt` > '$dt' AND `amount` IS NULL AND `game` = ".$game_id);
                $stat_zero_count[$gamename] = mysql_result($result2, 0, 'zerocount');
                $games_count_sum += $stat_zero_count[$gamename];
                mysql_free_result($result2);
            }
            $stat[$gamename] += $sum;
            $stat_count[$gamename] += $row->cnt;
            $summa += $sum;            
        }
        mysql_free_result($result);

        /*
        $items = $mikron->Queries->Query('PLAYLOG', null, new Criterion('dt', $dt, CR_MOREOREQUAL));
        while($item = $items->fetch())
        {
            $gamename = $item->game->value->name->value;
            $amount = $item->amount->value;
            if(!array_key_exists($gamename, $stat))
            {
                $stat[$gamename] = 0;
                $stat_count[$gamename] = 0;
            }
            $stat[$gamename] += $amount;
            $stat_count[$gamename] += 1;
            $summa += $amount;
        }
        */

        // Подсчет кол-ва регистраций сегодня
        $cr = new Criterion('dt', date($mikron->Constants->DateFormatMySQL, time()), CR_MORE);
        $new_users_count = $mikron->Queries->Query('T_USER', null, $cr, null, null, null, true);

        if(count($stat) > 0)
        {
            ?><table><tr><td>{{nicewindow style=silver caption="<?php echo "Статистика<br />на $dt2:" ?>"}}<?php
            $tbl = new html_table(null, 'table4', '100%', 0, 4, Array('Игра', 'Затраты', 'Игр', '+Пустых'));
                foreach($stat as $name => $amount)
                {
                    $amount /= 100;
                    $tbl->newCol($name);
                    $tbl->newCol($amount.' руб.');
                    $tbl->newCol($stat_count[$name]-$stat_zero_count[$name]);
                    $tbl->newCol($stat_zero_count[$name]);
                    $games_count += $stat_count[$name];
                }
            $tbl->end();
            echo "&nbsp;<br />Общая сумма: ".round($summa/100, 2), ' руб.
            <br />Сумма в проекте: '.round($sum_in_project/100, 2), ' руб.
            <br />Игр: '.$games_count.' шт ('.$games_count_sum.' пустых, '.round(($games_count_sum/$games_count) * 100, 1).'%)
            <br />Регистраций: '.$new_users_count.'
            <br /><a href="http://my.statcounter.com/project/standard/stats.php?project_id=3616173&guest=1">Внешняя статистика посещений</a>
            {{/nicewindow}}</table>';
        }
        else
        {
            ?>Список пуст.<?php
        }

        $tbl_main->newcol(null, false, false, null, null, null, 'top');

            echo '<h1>Все игры в этот день:</h1>';
            if(isset($_GET['showgamesstat']))
            {
                $items = $mikron->Queries->Query('PLAYLOG', null, new Criterion('dt', $dt, CR_MOREOREQUAL));
                $mikron->EntityManager->ShowList($items, false, false, false, false, true);
            }
            else
            {
                ?><a href="?showgamesstat">Показать</a><?php
            }

        ?><h1>Рефереры:</h1><?php

            if(isset($_GET['showreferers']))
            {
                $sum = 0;
                $referers = $mikron->Queries->Query('T_COUNTER', null, null, null, null, null, null, Array('referer', 'dt'));

                $ref_lastpage = Array();
                $ref_lastpage_time = Array();
                $pages = Array();
                while($ref = $referers->fetch())
                {
                    $referer = $ref->referer->value;
                    $host = parse_url($referer, PHP_URL_HOST);
                    if(!is_null($host))
                    {
                        if(!array_key_exists($host, $pages))
                        {
                            $pages[$host] = 1;
                        }
                        else
                        {
                            $pages[$host]++;
                        }
                        $ref_lastpage[$host] = $referer;
                        $ref_lastpage_time[$host] = $ref->dt->value;
                    }
                }
                if(count($pages) == 0)
                {
                    ?><font color="silver">Пусто</font><?php
                }
                else
                {
                    $t = new html_table(0, 'table4');
                    $t->addhead('Реферер (домен)');
                    $t->addhead('Хитов');
                    $t->addhead('Последний визит');
                    foreach($pages as $host => $count)
                    {
                        $page = $ref_lastpage[$host];
                        $title = $host;
                        if(strlen($title)> 64)
                        {
                            $title = substr($title, 0, 64).'...';
                        }
                        $t->newcol("<a href=\"$page\">$title</a><br />");
                        $t->newcol($count);
                        $t->newcol(MikronDateTime::BeautifulDate(strtotime($ref_lastpage_time[$host])));
                    }
                    $t->end();
                }
            }
            else
            {
                ?><a href="?showreferers">Показать</a><?php
            }
            
        $tbl_main->newrow();
        $tbl_main->newcol(null, false, false, null, null, null, null, null, 2);
        
            echo $mikron->Cache->TimedFunctionContent('InterestingStatistics', 'InterestingStatistics', 300);

        $tbl_main->newrow();
        $tbl_main->newcol(null, false, false, null, null, null, null, null, 2);
        
            ShorGraph();
        
        $tbl_main->end();
    
    }

    function ShorGraph()
    {
        global $mikron;
        /**
        * Графики
        */

        $first_counter = $mikron->Queries->Query('T_COUNTER', null, null, '`id` ASC', '0,1', null, false, Array('dt'));
        $first_counter = $first_counter->fetch();
        $start_date = $first_counter->dt->value;
        $stat_data = $mikron->Queries->Query('MINISTAT');
        $stat_days = Array();
        $new_users = Array();

        while($sd = $stat_data->fetch())
        {
            $dt = $sd->statdate->value;
            $dt = date($mikron->Constants->DateFormatMySQL, strtotime($dt));
            if(!in_array($dt, $stat_days))
            {
                $stat_days[] = $dt;
            }
        }

        $need_days = Array();
        for($i = strtotime($start_date); $i <= strtotime(date('d-m-Y')); $i += 86400)
        {
            $dt = date($mikron->Constants->DateFormatMySQL, $i);
            if(!in_array($dt, $stat_days))
            {
                $need_days[] = $dt;
            }
        }

        $today = null; //date($mikron->Constants->DateFormatMySQL);

        foreach($need_days as $nd)
        {
            $cr = new Criteria();
            $cr->add(new Criterion('dt', $nd, CR_MOREOREQUAL));
            $cr->add(new Criterion('dt', date($mikron->Constants->DateFormatMySQL, strtotime($nd)+86400), CR_LESS));
            
            $new_users[$nd] = $mikron->Queries->Query('T_USER', null, $cr, null, null, null, true);

            $logs = $mikron->Queries->Query('PLAYLOG', null, $cr, null, null, null, false, Array('amount', 'game'));
            $count_all = $logs->count();
            $count_zero = 0;
            $all_games_summa = 0;
            $games_count = Array(1=>0,2=>0,3=>0,4=>0,5=>0,6=>0,7=>0);
            $games_summa = Array(1=>0,2=>0,3=>0,4=>0,5=>0,6=>0,7=>0);
            while($log = $logs->fetch())
            {
                $amount = $log->amount->value;
                $all_games_summa += $amount;
                $game_id = $log->game->value->id;
                if($amount == 0)
                {
                    $count_zero++;
                }
                $games_count[$game_id]++;
                $games_summa[$game_id] += $amount;
            }

            if($nd != $today)
            {
                $ms = new MINISTAT();
                $ms->statdate->value = $nd;
                $ms->games_count->value = $count_all;
                $ms->games_summa->value = $all_games_summa;
                $ms->zerogames->value = $count_zero;
                $ms->newusers->value = $new_users[$nd];
                for($i=1; $i<8; $i++)
                {
                    $fieldname = 'game'.$i;
                    $ms->$fieldname->value = $games_count[$i];
                    $fieldname = 'game'.$i.'_amount';
                    $ms->$fieldname->value = $games_summa[$i];
                }
                $ms->Save();
            }
        }

        $stat_data = $mikron->Queries->Query('MINISTAT');
        $graph_users = Array();
        $graph_games = Array();
        $graph_zero_games = Array();

        $table = new html_table(null, 'table4', '100%', 0, 0, Array('Дата','Игр','Пустых','Сумма','Рег.','1руб','5руб','10руб','50руб','100руб','500руб','1000'));

        $stat_data->reset();
        while($sd = $stat_data->fetch())
        {
            $count_zero = $sd->zerogames->value;
            
            $graph_users[] = $sd->newusers->value;
            $graph_games[] = $sd->games_count->value;
            $graph_zero_games[] = $count_zero;

            $table->newcol(MikronDateTime::BeautifulDate(strtotime($sd->statdate->value), false), true);
            $table->newcol($sd->games_count->value);
            $games_count = $sd->games_count->value;
            $zero_percent = 0;
            if($games_count)
            {
                $zero_percent = $count_zero / $games_count;
            }
            $table->newcol($count_zero.' <font color="aaaaaa" style="font-size: .8em;">'.round($zero_percent * 100, 1).'%</font>', true);
            $table->newcol(round($sd->games_summa->value/100, 2), true);
            $table->newcol($sd->newusers->value);
            for($i=1; $i<=7; $i++)
            {
                $fieldname = 'game'.$i;
                $count = $sd->$fieldname->value;
                $fieldname = 'game'.$i.'_amount';
                $amount = $sd->$fieldname->value;
                $table->newcol($count.' <font color="aaaaaa" style="font-size: .8em;">'.round($amount / 100, 2).'р</font>', true);
            }
        }
        $table->end();

        $stat_data->reset();
        while($sd = $stat_data->fetch())
        {
            $count_zero = $sd->zerogames->value;
            $dt = MikronDateTime::BeautifulDate(strtotime($sd->statdate->value));
            $games_all = $sd->games_count->value;
            $zero_percent = 0;
            if($sd->games_count->value)
            {
                $zero_percent = ($count_zero / $sd->games_count->value) * 100;                
            }
            $all_summa = $sd->games_summa->value;
            $users = $sd->newusers->value;
            for($i=1; $i<8; $i++)
            {
                $fieldname = 'game'.$i;
                $count = $sd->$fieldname->value;
                $fieldname = 'game'.$i.'_amount';
                $amount = $sd->$fieldname->value;
            }
        }
        
        $graph_users = array_reverse($graph_users);
        $graph_games = array_reverse($graph_games);
        $graph_zero_games = array_reverse($graph_zero_games);
        
        $graph = CreateGraph(512, 240);
        $color_green = imageColorAllocate($graph, 0, 200, 0);
        $color_blue = imageColorAllocate($graph, 0, 0, 200);
        $color_red = imageColorAllocate($graph, 200, 0, 0);
        DrawGraph($graph, $graph_users, $color_green);
        DrawGraph($graph, $graph_games, $color_blue);
        DrawGraph($graph, $graph_zero_games, $color_red, max($graph_games));
        SaveGraph($graph, dirname(__FILE__).'/graph2.png');
        
        ?>&nbsp;<h1>Графики:</h1>
        <img src="/adminpanel/graph2.png">
        <br /><font color="008800">Зарегистрировано игроков</font>,
        <font color="000088">Количество игр</font>,
        <font color="880000">Количество пустых игр</font>
        

        <?php
    
    }

    /*
        echo '{{nicewindow style=silver caption="Товарищи Засиралкины"}}';
        $dt2 = quote_smart(date($mikron->Constants->DateFormatMySQL, time() - 86400 * 3));
        $result = mysql_query('select count(*) cnt, `user`, `dt` FROM PLAYLOG WHERE `dt` > '.$dt2.' GROUP by DATE(`dt`), user HAVING cnt > 9 ORDER by `dt` DESC, `cnt` DESC, `user` ASC');
        $t2 = new html_table(null, 'table4', '100%', 0, 4, Array('Дата', 'Кол-во игр', 'Логин (ID)', 'E-mail', 'Выигрыши', 'Реферальные'));
        while($row = mysql_fetch_object($result))
        {
            $user = $mikron->Queries->Query('T_USER', $row->user)->fetch();
            $t2->newcol(MikronDateTime::BeautifulDate(strtotime($row->dt), false));
            $t2->newcol($row->cnt, true, 'right');
            $t2->newcol($user->login->value. ' <font color="cccccc">('. $row->user.')</font>');
            $t2->newcol($user->email->value);
            if($user->winamount->value > 0)
            {
                $t2->newcol(round($user->winamount->value/100,2).'<font color="cccccc"> руб.</font>');
            }
            else
            {
                $t2->newcol('<font color="cccccc">пусто</font>');
            }
            if($user->refamount->value > 0)
            {
                $t2->newcol(round($user->refamount->value/100,2).'<font color="cccccc"> руб.</font>');
            }
            else
            {
                $t2->newcol('<font color="cccccc">пусто</font>');
            }
        }
        $t2->end();
        echo '{{/nicewindow}}';
    */

return;

   // header("Content-type:  image/png");
   
   function SaveGraph($image, $filename)
   {
       imagePNG($image, $filename);
   }
   
   function DrawGraph($image, $items, $color, $max_value = null)
   {

        $borderLeft = 8;
        $borderBottom = 8;
        $borderTop = 8;
        $borderRight = 8;
        $cols = 20;
        $rows = 15;

        $diagramWidth = imagesx($image);
        $diagramHeight = imagesy($image);

        $dW = $diagramWidth - ($borderLeft + $borderRight);
        $dH = $diagramHeight - ($borderBottom + $borderTop);

        // толщина линии
        imagesetthickness($image, 2);

        $x = $borderLeft;
        $y = -1;
        $count_all = 0;
        $count_days = 0;
        $max = 0;
        $days = count($items);

        if(is_null($max_value))
        {
            foreach($items as $item)
            {
                if($item > $max)
                {
                    $max = $item;
                }
            }
        }
        else
        {
            $max = $max_value;
        }

        // рисуем график
        foreach($items as $item)
        {
            $number = $item;
            $count_all += $number;
            $newy = 0;
            if($max != 0)
            {
                $newy = $dH - ($number / $max) * $dH;                
            }
            if($y < 0){$y = $newy;}
            if($x == $borderLeft)
            {
                imageLine($image, $x, $newy+$borderTop, $x, $y+$borderTop+1, $color);
            }
            else
            {
                imageLine($image, $x, $newy+$borderTop, $x-($dW/($days-1)), $y+$borderTop+1, $color);
            }
            $y = $newy;
            $x += ($dW / ($days-1));
        }

        ////////////////////////////////////////

        /*
        $stat = Array();
        $stat[] = "Max: ".$max.", $maxday";
        $stat[] = "Today: $hosts_today ($hosts_total)";
        $stat[] = $startperiod." - ".$endperiod." ($days)";

        // создаем изображение
        $image2 = imageCreate(250, ($dH/$rows)*count($stat));
        imagealphablending($image2, true);
        imagecopymerge($image, $image2, $borderLeft, $borderTop, 0, 0, ImageSX($image2), ImageSY($image2), 32);

        for($i=0; $i<(count($stat)); $i += 1)
        {
            imageString($image, 4, $borderLeft+4, $borderTop+($dH/$rows)*$i, $stat[$i], $colorGridTextHighLight);
        }
        */

        // делаем цвет фона прозрачным
        //imageColorTransparent($image, $colorBackgr);

        // выводим изображение
        
   }

   function CreateGraph($w, $h)
   {

        $diagramWidth = $w;
        $diagramHeight = $h;
        $borderLeft = 4;
        $borderBottom = 4;
        $borderTop = 4;
        $borderRight = 4;
        $cols = 20;
        $rows = 15;
        $dW = $diagramWidth - ($borderLeft + $borderRight);
        $dH = $diagramHeight - ($borderBottom + $borderTop);
        $hosts_array = Array();

        // создаем изображение
        $image = imageCreate($diagramWidth, $diagramHeight);
        imagealphablending($image,true);

           // Регистрируем используемые цвета
        $colorGridText = imageColorAllocate($image, 0, 0, 0);
        $colorGridTextHighLight = imageColorAllocate($image, 255, 255, 255);
        $colorGridHostsHighligh = imageColorAllocate($image, 230, 255, 200);
        $ruleLinesColor = imageColorAllocate($image, 200, 200, 200);
        $colorBackgr = imageColorAllocate($image, 240, 240, 240);
        $colorBackgrIn = imageColorAllocate($image, 255, 255, 255);
        $colorCross = imageColorAllocate($image, 255, 0, 0);
        $colorCrosshair = imageColorAllocate($image, 200, 200, 200);
        $colorGridHosts = imageColorAllocate($image, 0, 200, 0);
        $colorGridProxys = imageColorAllocate($image, 255, 128, 0);

        // рисование фона
        // заливаем цветом фона
        imageFilledRectangle($image, 0, 0, $diagramWidth - 1, $diagramHeight - 1, $colorBackgr);
        imageFilledRectangle($image, $borderLeft, $borderTop, $dW+$borderLeft, $dH+$borderTop, $colorBackgrIn);
        imagesetthickness($image, 2);
        imageLine($image, $borderLeft, $borderTop, $borderLeft, $borderTop+$dH, $ruleLinesColor);
        imageLine($image, $borderLeft, $borderTop+$dH, $borderLeft+$dW, $borderTop+$dH, $ruleLinesColor);

        ////////////////////////////////////////

        $x = $borderLeft;
        $y = -1;
        $count_all = 0;
        $count_days = 0;

        // толщина линии
        imagesetthickness($image, 1);

        /*
        // Горизонтальные линии
        for($i=0; $i<($dH); $i += ($dH/$rows))
        {
        // значение деления шкалы
        $rule = $max - round(($i/$dH) * $max, 0);
        imageLine($image, $borderLeft, $i+$borderTop, $dW+$borderLeft, $i+$borderTop, $colorCrosshair);
        imageString($image, 4, 5, $i + $borderTop - 7, $rule, $colorGridText);
        }

        // Вертикальные линии
        for($i=0; $i<=($dW); $i += ($dW/$cols))
        {
        // значение деления шкалы
        $rule = round(($i/$dW) * ($days-1), 3);
        imageLine($image, $i + $borderLeft, $borderTop, $i+$borderLeft, $borderTop+$dH, $colorCrosshair);
        $sp = strtotime($startperiod);
        $sp_add = MikronDateTime::DateAdd("d", $rule, $sp);
        $dtday  = date('j', $sp_add);
        $dtmonth = substr(date("F", $sp_add), 0, 3);
        imageString($image, 2, $i + $borderLeft, $borderTop + $dH + 2, $dtday, $colorGridText);
        imageString($image, 2, $i + $borderLeft-5, $borderTop + $dH + 2 + 9, $dtmonth, $colorGridText);
        }*/

        return $image;

   }
    
?>